#coding=utf-8
#LightCam 进程状态查看程序
#init by hfh 20150212

import multiprocessing,subprocess
import socket,os,time,re
import lc_libs

def func(ProcessName,ScriptsName,agent_hostname):
	
	#定义命令
	#comd="ps -ef|grep -w '"+str(ScriptsName)+"'|grep -v 'grep'|awk '{if ( $3 == 1 ) print $0}'"
	comd="ps -eo user,pid,ppid,etime,args|grep -w '"+str(ScriptsName)+"'|grep -v 'grep'|awk '{if ( $3 == 1 ) print $0}'"
	
	#执行命令
	popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)

	#等待命令执行完毕
	while True:
		if popen.poll()==None:
			time.sleep(0.01)
			continue
		else:
			break
			
	#获取命令执行结果
	line=popen.stdout.read().strip("\n").strip("\r").split()
	
	status=""
	user=""
	pid=""
	etime=""
	
	if len(line)==0:
		status="Dead"
	else:
		status="Running"
		user=line[0]
		pid=line[1]
		etime=line[3]
	
	return [ProcessName,agent_hostname,status,user,pid,etime]
	
if __name__ == "__main__":

	width = 90
	column_width = 15
	format = ' %-*s%-*s%-*s%-*s%-*s%-*s'

	print '-' * width
	print format % (column_width,'Service',column_width,'Host',column_width,'Status',column_width,'User',column_width,'PID',column_width,'ETIME')
	print '-' * width

	agent_hostname=lc_libs.lc_gethostname()

	for line in open("../conf/lc_status.conf"):
		if line[0] == '#' or line.split("\t")[0] not in (agent_hostname,'default'):
			continue
		ProcessName=line.strip('\n\r').split('\t')[1]
		ScriptsName=line.strip('\n\r').split("\t")[2]
		[service,host,status,user,pid,etime]=func(ProcessName,ScriptsName,agent_hostname)
		print format % (column_width,service,column_width,host,column_width,status,column_width,user,column_width,pid,column_width,etime)

	print '-' * width
